package cn.edu.seu.cose.qol.model.dao.config;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

class PropertiesReader {
	
	private static final Map<String, PropertiesReader> READER_POOL;
	static {
		READER_POOL = new HashMap<String, PropertiesReader>();
	}
	
	private String _identifier;
	
	private Properties _properties;
	
	public static synchronized PropertiesReader getInstance(String filePath)
			throws IOException {
		if (READER_POOL.containsKey(filePath)) {
			return READER_POOL.get(filePath);
		}
		
		PropertiesReader newInstance = new PropertiesReader(filePath);
		READER_POOL.put(filePath, newInstance);
		return newInstance;
	}
	
	protected PropertiesReader(String filePath) throws IOException {
		_identifier = filePath;
		
		createIfDoNotExist(filePath);
		
		InputStream in = new BufferedInputStream(new FileInputStream(filePath));
		_properties = new Properties();
		_properties.load(in);
	}
	
	@Override
	protected void finalize() {
		READER_POOL.remove(_identifier);
	}
	
	public String getProperty(String key) {
		return _properties.getProperty(key);
	}
	
	private void createIfDoNotExist(String filePath) {
		File propertiesFile = new File(filePath);
		
		if (!propertiesFile.exists()) {
			propertiesFile.mkdir();
		}
	}

}
